window.onload= function(){

    var inputText = document.getElementById("inputText"),
        outnode = document.getElementById("outputNode"),
        showCode = document.getElementById('showMathCode'),
        selColor = document.getElementById('selColor'),
        oulFormulas = document.getElementById('formulas'),
        oliFormula,
        color,
        fontsize = 1.5;

    produceKeyBord();
    clearInput();
    doSelectColor();

    document.onkeyup = doKeyUp;
    document.getElementById('clearInput').onclick=clearInput;
    document.getElementById('copyMathCode').onclick=copyMathCode;
    document.getElementById('addfontSize').onclick = document.getElementById('decreasefontSize').onclick = setFontSize;
    selColor.onclick = doSelectColor;
    document.getElementById('submit').onclick = dosubmit;

    oulFormulas.ondblclick = doModifyFormula;

    function display()
    {
        var str = inputText.value;
        str=str.replace(/`/g, "");
        inputText.value=str;
        str="`"+str+"`";
        var len = outnode.childNodes.length;
        for (var i=0; i<len; i++){
            outnode.removeChild(outnode.firstChild);
        }
        outnode.appendChild(document.createTextNode(str));

        AMprocessNode(outnode);
        setFontSize();
        doSelectColor();


        if (!inputText.value) {
            showCode.value = '';
            showCode.style.display = 'none';
            //showCode.setAttribute('class','show-code');
        }
        inputText.focus();
    }

    function insertHTML(html)
    {
        inputText.focus();
        if (document.selection) { //IE
            if (inputText.document.selection.type.toLowerCase() != "none") { //如果有文字被选中
                inputText.document.selection.clear();
            }
            var txt=inputText.document.selection.createRange();
            txt.text = html ;
        }
        else if(window.getSelection){
            if (inputText.selectionStart == inputText.selectionEnd) { //如果没有选中
                inputText.value = html;
            } else {
                inputText.value = inputText.value.substr(0,inputText.selectionStart) + html +  inputText.value.substr(inputText.selectionEnd);
            }
        }
    }
    var his = [];
    /**
     * 生成操作代码
     */
    function addCode(opera)
    {
        var inputVal= inputText.value,
            cursorPos='',
            inputVal1='',
            inputVal2='',
            isSel = true;
            console.log(inputVal);
       
        console.log(opera);
        if(opera != "←"){
            his.push(inputVal);
            console.log(his);
        }


        if (document.selection) { //IE
            inputVal = inputText.document.selection.createRange().text;
        } else if(window.getSelection){   // Firefox support
            inputVal = inputText.value.substr(inputText.selectionStart, inputText.selectionEnd - inputText.selectionStart)
        }
        if (!inputVal) { //如果没选中
            isSel = false;
            cursorPos = inputText.selectionStart;
            inputVal1 = inputText.value.substr(0,cursorPos);
            inputVal2 = inputText.value.substr(cursorPos);
        }

        inputText.focus();
        switch (opera)
        {

            case '=':
            case "+":
            case "-":
            case "×":
            case "÷":
            case "±":
            case "≌":
            case "≠":
            case "≈":
            case "∝":
            case "∞":
            case "≡":
            case '<':
            case '>':
            case "≥":
            case "≤":
            case "_":
            case "^":
            case "->":
            case "{":
            case "}":
            case "[":
            case "]":
            case "(":
            case ")":
            case '〈':
            case'〉':
            case "⋅":
            case '∩':
            case '∪':
            case '∧':
            case '∨':
            case "∉":
            case "∈":
            case '⊂':
            case  '⊃':
            case '⊆':
            case '⊇':
            case '...':
            case '⋱':
            case '⋮':

            case '∀':
            case '∃':
            case '∂':
            case   'α':
            case   'β':
            case   'δ':
            case   'Δ':
            case   '∇':
            case   'ε':
            case   'η':
            case   'γ':
            case   'Γ':
            case   'λ':
            case   'μ':
            case   'ν':
            case   'υ':
            case   'ω':
            case   'Ω':
            case   'φ':
            case   'ϕ':
            case   'Φ':
            case   'ψ':
            case   'Ψ':
            case   'ρ':
            case   'σ':
            case   'τ':
            case   'θ':
            case   'Θ':
            case   'ξ':


            //前置符号
            case "lim_":
            case "f":
            case '∮':
            case "sin":
            case "cos":
            case "∫":
                inputVal = !isSel ? inputVal1 + opera + inputVal2: inputVal + opera;
                insertHTML(inputVal);
                break;
            case 'space':
                inputVal = !isSel ? inputVal1 + ' ' + inputVal2: inputVal + ' ';
                insertHTML(inputVal);
                break;
            case "/":
                inputVal = !isSel ? inputVal1 + ' a/b ' + inputVal2: inputVal + opera;
                insertHTML(inputVal);
                break;
            case "sqrt":
                inputVal = !isSel ? inputVal1 + ' sqrt()' + inputVal2: inputVal + ' sqrt()';
                insertHTML(inputVal);
                break;
            case "root":
                inputVal = !isSel ? inputVal1 + ' root()()' + inputVal2: inputVal + ' root()()';
                insertHTML(inputVal);
                break;
            case "∑":
                inputVal = !isSel ? inputVal1 + ' sum ' + inputVal2: ' sum '+inputVal;
                insertHTML(inputVal);
                break;
            case "∑_^":
                inputVal = !isSel ? inputVal1 + ' sum_a^b ' + inputVal2: 'sum_a^b'+inputVal;
                insertHTML(inputVal);
                break;

            case "∫_^":
                inputVal = !isSel ? inputVal1 + ' int_a^bf(x)dx ' + inputVal2: 'int_a^bf(x)dx'+inputVal;
                insertHTML(inputVal);
                break;


            //case "∑^":
            //    inputVal = !isSel ? inputVal1 + '^' + inputVal2: inputVal + '^';
            //    insertHTML(inputVal);
            //    break;

            case "π":

                inputVal = !isSel ? inputVal1 + 'pi' + inputVal2: inputVal + 'pi';
                insertHTML(inputVal);
                break;

            case "∏":

                inputVal = !isSel ? inputVal1 + 'prod' + inputVal2: inputVal + 'prod';
                insertHTML(inputVal);
                break;

            //选中
            case "()":

                insertHTML("("+inputVal+")");
                break;

            case "[_]":
                if (isSel) {
                    if(inputVal.split(',').length==4)
                    {
                        insertHTML("[["+inputVal.split(',')[0]+","+inputVal.split(',')[1]+"],["+inputVal.split(',')[2]+","+inputVal.split(',')[3]+"]]");
                    }
                } else {
                    insertHTML(inputVal1 + ' [[a,b],[c,d]]' + inputVal2);
                }

                break;

             case '←':
            // var input = inputText.value;

            // input = input.substring(0,input.length-1);

            // inputText.value = input;
            // var input = inputText.value;

            // input = input.substring(0,input.length-1);

            // inputText.value = input;
           if(his.length){
                inputText.value = his[his.length-1];
            
                his.length = his.length-1;
            }
                break;

            case "(_)":
                if (isSel) {
                    if(inputVal.split(',').length==2)
                    {
                        insertHTML("(("+inputVal.split(',')[0]+"),("+inputVal.split(',')[1]+"))");
                    }
                    if(inputVal.split(',').length==4)
                    {
                        insertHTML("(("+inputVal.split(',')[0]+","+inputVal.split(',')[1]+"),("+inputVal.split(',')[2]+","+inputVal.split(',')[3]+"))");
                    }
                } else {
                    insertHTML(inputVal1 + ' ((a,b),(c,d))' + inputVal2);
                }

                break;

            case "{:}":
                if (isSel) {
                    var len = inputVal.split(',').length;


                    if(inputVal.split(',').length==4)
                    {
                        insertHTML("{("+inputVal.split(',')[0]+","+inputVal.split(',')[1]+"),("+inputVal.split(',')[2]+","+inputVal.split(',')[3]+"):}");
                    }
                    if(inputVal.split(',').length==6)
                    {
                        insertHTML("{("+inputVal.split(',')[0]+","+inputVal.split(',')[1]+"),("+inputVal.split(',')[2]+","+inputVal.split(',')[3]+"),("+inputVal.split(',')[4]+","+inputVal.split(',')[5]+"):}");
                    }
                } else {
                    insertHTML(inputVal1 + ' {(a,b),(c,d):}' + inputVal2);
                }
                break;
            //选中  end
        }
        display();
    }

    function produceKeyBord()
    {
        var keys=
            [
                //运算符
                "+", "+","",
                "-", "-","",
                "×", "xx","",
                "÷", "-:","",
                "⋅", "*","",
                //"∑","sum","",
                "∏","prod","",
                '∩','nn','',
                '∪','uu','',
                '∧','^^','',
                '∨','∨v','',
                //关系符
                '=','=','',
                "±", "+-","",
                "≌", "~=","",
                "≠", "!=","",
                "≈", "~~","",
                "≡","-=","",
                '<','<','',
                '>','>','',
                "≥",">=","",
                "≤","<=","",
                "∝", "prop","",
                "∉","!in","",
                "∈","in","",
                '⊂','sub','',
                '⊃','sup','',
                '⊆','sube','',
                '⊇','supe','',
                '...','...','',
                '⋮','vdots','',
                '⋱','ddots','',
                //∈∩∪∮∫
                "(","(","",
                ")",")","",
                '[','[','',
                ']',']','',
                "{","{","",
                "}","}","",
                '〈','(:','',
                '〉',':)','',
                '←','字符回删','',
                //混合运算符
                '∫','int','',
                '∮','oint','',
                "∞", "无穷","",
                "f","f","05.gif",
                "lim_","lim_","13.gif",
                "->","->","06.gif",
                "sqrt","开方","18.png",
                "root","开方","19.png",
                "sin","正弦","",
                "cos","余弦","",
                '∀','任意','',
                '∃','存在','',
                "/","分式","14.png",
                "_","下标","16.png",
                "^","上标","15.png",
                "∑_^","∑上下标","17.png",
                "∫_^","定积分","20.png",
                //"∑^","∑上标","11.gif",
                "()","括号","",
                "[_]","矩阵","03.gif",
                "(_)","(_)","04.gif",
                "{:}","{:}","",
                '←','字符回删','',
                '∂','del','',
                //希腊字母
                'α','alpha','',
                'β','beta','',
                'δ','delta','',
                '∇','grad','',
                'Δ','Delta','',
                'λ','lambda','',
                'ε','epsilon','',
                'η','eta','',
                'γ','gamma','',
                'Γ','Gamma','',
                'μ','mu','',
                'ν','nu','',
                'υ','','',
                'ω','omega','',
                'Ω','Omega','',
                'φ','phi','',
                'ϕ','varphi','',
                'Φ','Phi','',
                'π','pi','',
                'ψ','ψ','',
                'Ψ','Ψ','',
                'ρ','ρ','',
                'σ','σ','',
                'τ','τ','',
                'θ','theta','',
                'Θ','Theta','',
                'ξ','ξ','',
                '←','字符回删',''
                
            ];
        for (i=0;i<keys.length-1 ;i++ )
        {
            if(i%3==0)
            {   
                var j = i / 3;
                var button = document.createElement("button");
                button.name=keys[i];
                if(keys[i+2]=="")
                {
                    button.value=keys[i];
                    button.innerHTML=keys[i];
                }
                else
                {
                   button.value="<img src=ico/"+keys[i+2]+">";
                   button.innerHTML="<img src=ico/"+keys[i+2]+">";
                }
                button.title=keys[i+1];
                button.onclick = function() {addCode(this.name)};

                if(j < 39) {
                    document.getElementById("formula1").appendChild(button);
                } else if (j < 61) {
                    document.getElementById("formula2").appendChild(button);
                } else {
                    document.getElementById("formula3").appendChild(button);
                }
                
            }
        }

        formulaTab();
    }

    function doKeyUp()
    {
        if((e.keyCode>=37&&e.keyCode<=40)||e.keyCode==8||e.keyCode==46||e.keyCode==32) {}
        else {
            display();
        }
    }

    /**
     * 公式分类 点击
     */
    function formulaTab () {
        var tabNav = $(".formula-wrp .nav-item");
        var tabCont = $(".formula-wrp .cont-item");
        tabNav.eq(0).addClass('active');
        tabCont.eq(0).addClass("active");
        tabNav.click(function (){
            var contId = $(this).data('cont');
            var index = $(this).index();
            tabNav.removeClass("active");
            tabCont.removeClass("active");
            $(this).addClass("active");
            tabCont.eq(index).addClass("active");
        });
    }

    /**
     * 复制公式代码
     */
    function copyMathCode()
    {
        var str = outnode.innerHTML;
        showCode.value = str;
        showCode.style.display = 'block';
        //showCode.setAttribute('class','show-code block');
    }

    /**
     * 点击‘清空’按钮
     */
    function clearInput()
    {
        inputText.value='';
        display();
    }

    function setFontSize(e) {
        var ms = outnode.getElementsByTagName('mstyle');
        var font = parseFloat(ms[0].getAttribute('mathsize'));
        if (!e) {
            ms[0].setAttribute('mathsize', fontsize + 'em');
            return ;
        }
        var tar = e.target;
        var id = tar.getAttribute('id');
        if (id == 'addfontSize') {
            fontsize = (font + 0.5) > 5 ? 5 : (font + 0.5);
        } else if (id == 'decreasefontSize') {
            fontsize = (font - 0.5) < 0.5 ? 0.5 : (font - 0.5);
        }
        ms[0].setAttribute('mathsize',fontsize + 'em');

        fontsize = 1.5;
    }
    function doSelectColor() {
        var ms = outnode.getElementsByTagName('mstyle');
        //if (color) {
        //    ms[0].setAttribute('mathcolor',color);
        //} else {
        //    ms[0].setAttribute('mathcolor',selColor.value);
        //}
        color = color ? color :selColor.value;
        ms[0].setAttribute('mathcolor',color);
        color ='';
    }
    function dosubmit(){
        var str = outnode.innerHTML;
        if (!str) return ;
        clearInput();
        if (oliFormula) {
            oliFormula.innerHTML = str;
            oliFormula = document.getElementById('');
            return ;
        }
        var oli=document.createElement("li");
        oli.title = '双击修改';
        oli.className = 'formula';
        oli.id = 'formula' + (oulFormulas.childNodes.length + 1);
        oli.innerHTML = str;
        oulFormulas.appendChild(oli);
    }
    function doModifyFormula(e) {
        var tar = e.target;
        var formulaTitle = tar.firstChild.getAttribute('title');
        oliFormula = document.getElementById(tar.id);
        inputText.value = formulaTitle;
        color = tar.getElementsByTagName('mstyle')[0].getAttribute('mathcolor');
        fontsize = parseFloat(tar.getElementsByTagName('mstyle')[0].getAttribute('mathsize'));
        display();
    }
};
